package org.yun.octopus.base.core;

import org.yun.octopus.base.config.Cfg;
import javax.annotation.PostConstruct;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;


/**
 * @author liyunfeng31
 */
public abstract class AsyncHelper {

    /**
     * 队列大小
     */
    protected static final int CACHE_SIZE = 500;

    /**
     * cmd queue
     */
    protected static final BlockingQueue<MarkCmd> QUEUE = new LinkedBlockingDeque<>();


    protected static final ExecutorService SERVICE = Executors.newSingleThreadExecutor();


    private static final AtomicBoolean WILL_EXIT = new AtomicBoolean(false);


    private static final Object OBJ = new Object();


    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                WILL_EXIT.set(true);
                synchronized (OBJ){
                    OBJ.wait();
                }
                SERVICE.shutdown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }));
    }



    /**
     * 入队
     * @param group 业务组
     * @param bizNo 业务编号
     * @param stepNo 步骤编号
     * @param code 结果标识
     * @return success
     */
    public static boolean offer(String group, String bizNo, int stepNo, int code, String childNo){
        return QUEUE.offer(new MarkCmd(group, bizNo, stepNo, code, childNo));
    }


    public static boolean offer(String group, String bizNo){
        return QUEUE.offer(new MarkCmd(group, bizNo));
    }


    @PostConstruct
    public void consume(){
        SERVICE.submit(()->{
            while (true){
                try {
                    batchSave();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if(WILL_EXIT.get()){
                    Cfg.markAsync = true;
                    if(QUEUE.size() == 0){
                        synchronized (OBJ){
                            OBJ.notify();
                        }
                        break;
                    }
                }
            }
        });
    }

    public void batchSave() throws InterruptedException {}

}
